package com.example.rocketmq.controller;

import com.example.rocketmq.model.Message;
import com.example.rocketmq.service.MessageProducerService;
import com.example.rocketmq.service.SentinelRateLimitConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Sentinel限流测试控制器
 * 专门用于测试Sentinel在RocketMQ消息消费过程中的限流机制
 * 通过发送消息到RocketMQ，然后观察Sentinel消费者服务的限流效果
 * 
 * @author demo
 */
@Slf4j
@RestController
@RequestMapping("/api/sentinel")
public class SentinelTestController {

    @Autowired
    private MessageProducerService messageProducerService;

    @Autowired
    private SentinelRateLimitConsumerService sentinelConsumerService;

    // 测试计数器 - 记录发送和消费情况
    private final AtomicInteger messagesSent = new AtomicInteger(0);
    private final AtomicInteger messagesConsumed = new AtomicInteger(0);
    private final AtomicLong totalSent = new AtomicLong(0);
    private final AtomicLong totalConsumed = new AtomicLong(0);

    /**
     * 测试Sentinel限流 - 发送消息到RocketMQ
     * 通过发送消息到RocketMQ，测试Sentinel消费者服务的限流效果
     */
    @PostMapping("/test-rate-limit")
    public ResponseEntity<Map<String, Object>> testRateLimit(@RequestBody Map<String, Object> request) {
        try {
            Integer messageCount = (Integer) request.get("count");
            if (messageCount == null || messageCount <= 0) {
                messageCount = 100;
            }

            log.info("开始测试Sentinel限流，发送消息数量: {}", messageCount);
            
            final int finalCount = messageCount;
            new Thread(() -> {
                try {
                    performSentinelRateLimitTest(finalCount);
                } catch (Exception e) {
                    log.error("Sentinel限流测试失败", e);
                }
            }).start();

            Map<String, Object> response = new HashMap<>();
            response.put("message", "Sentinel限流测试已启动，正在发送消息到RocketMQ");
            response.put("messageCount", messageCount);
            response.put("timestamp", System.currentTimeMillis());
            response.put("testType", "sentinel_rate_limit_test");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("启动Sentinel限流测试失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

//    /**
//     * 测试Sentinel限流 - 持续压力测试
//     * 持续发送消息到RocketMQ，测试Sentinel消费者的限流稳定性
//     */
//    @PostMapping("/test-pressure")
//    public ResponseEntity<Map<String, Object>> testPressure(@RequestBody Map<String, Object> request) {
//        try {
//            Integer duration = (Integer) request.get("duration");
//            Integer messagesPerSecond = (Integer) request.get("messagesPerSecond");
//
//            if (duration == null || duration <= 0) {
//                duration = 60;
//            }
//            if (messagesPerSecond == null || messagesPerSecond <= 0) {
//                messagesPerSecond = 10;
//            }
//
//            log.info("开始Sentinel压力测试，持续时间: {}秒, 每秒消息数: {}", duration, messagesPerSecond);
//
//            final int finalDuration = duration;
//            final int finalMps = messagesPerSecond;
//            new Thread(() -> {
//                try {
//                    performSentinelPressureTest(finalDuration, finalMps);
//                } catch (Exception e) {
//                    log.error("Sentinel压力测试失败", e);
//                }
//            }).start();
//
//            Map<String, Object> response = new HashMap<>();
//            response.put("message", "Sentinel压力测试已启动，持续发送消息到RocketMQ");
//            response.put("duration", duration);
//            response.put("messagesPerSecond", messagesPerSecond);
//            response.put("timestamp", System.currentTimeMillis());
//            response.put("testType", "sentinel_pressure_test");
//
//            return ResponseEntity.ok(response);
//        } catch (Exception e) {
//            log.error("启动Sentinel压力测试失败", e);
//            Map<String, Object> errorMap = new HashMap<>();
//            errorMap.put("error", e.getMessage());
//            return ResponseEntity.internalServerError().body(errorMap);
//        }
//    }

    /**
     * 获取Sentinel测试统计信息
     */
    @GetMapping("/test-stats")
    public ResponseEntity<Map<String, Object>> getTestStats() {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("messagesSent", messagesSent.get());
            response.put("messagesConsumed", messagesConsumed.get());
            response.put("totalSent", totalSent.get());
            response.put("totalConsumed", totalConsumed.get());
            response.put("sentinelConsumerStats", sentinelConsumerService.getConsumptionStats());
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取Sentinel测试统计信息失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

    /**
     * 重置测试计数器
     */
    @PostMapping("/reset-counters")
    public ResponseEntity<Map<String, Object>> resetCounters() {
        try {
            messagesSent.set(0);
            messagesConsumed.set(0);
            totalSent.set(0);
            totalConsumed.set(0);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "测试计数器已重置");
            response.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("重置测试计数器失败", e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(errorMap);
        }
    }

//    /**
//     * 测试Sentinel限流 - 突发流量测试
//     * 突发发送大量消息到RocketMQ，测试Sentinel消费者的限流响应
//     */
//    @PostMapping("/test-burst")
//    public ResponseEntity<Map<String, Object>> testBurst(@RequestBody Map<String, Object> request) {
//        try {
//            Integer burstSize = (Integer) request.get("burstSize");
//            if (burstSize == null || burstSize <= 0) {
//                burstSize = 50;
//            }
//
//            log.info("开始Sentinel突发流量测试，突发消息数量: {}", burstSize);
//
//            final int finalBurstSize = burstSize;
//            new Thread(() -> {
//                try {
//                    performSentinelBurstTest(finalBurstSize);
//                } catch (Exception e) {
//                    log.error("Sentinel突发流量测试失败", e);
//                }
//            }).start();
//
//            Map<String, Object> response = new HashMap<>();
//            response.put("message", "Sentinel突发流量测试已启动，突发发送消息到RocketMQ");
//            response.put("burstSize", burstSize);
//            response.put("timestamp", System.currentTimeMillis());
//            response.put("testType", "sentinel_burst_test");
//
//            return ResponseEntity.ok(response);
//        } catch (Exception e) {
//            log.error("启动Sentinel突发流量测试失败", e);
//            Map<String, Object> errorMap = new HashMap<>();
//            errorMap.put("error", e.getMessage());
//            return ResponseEntity.internalServerError().body(errorMap);
//        }
//    }

//    /**
//     * 测试Sentinel限流配置
//     * 发送消息到RocketMQ，验证Sentinel消费者的限流规则配置
//     */
//    @PostMapping("/test-config")
//    public ResponseEntity<Map<String, Object>> testConfig(@RequestBody Map<String, Object> request) {
//        try {
//            Integer testCount = (Integer) request.get("testCount");
//            if (testCount == null || testCount <= 0) {
//                testCount = 20;
//            }
//
//            log.info("开始测试Sentinel限流配置，测试消息数量: {}", testCount);
//
//            final int finalCount = testCount;
//            new Thread(() -> {
//                try {
//                    performConfigTest(finalCount);
//                } catch (Exception e) {
//                    log.error("Sentinel配置测试失败", e);
//                }
//            }).start();
//
//            Map<String, Object> response = new HashMap<>();
//            response.put("message", "Sentinel配置测试已启动，发送消息到RocketMQ验证限流规则");
//            response.put("testCount", testCount);
//            response.put("timestamp", System.currentTimeMillis());
//            response.put("testType", "config_test");
//
//            return ResponseEntity.ok(response);
//        } catch (Exception e) {
//            log.error("启动Sentinel配置测试失败", e);
//            Map<String, Object> errorMap = new HashMap<>();
//            errorMap.put("error", e.getMessage());
//            return ResponseEntity.internalServerError().body(errorMap);
//        }
//    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "Sentinel Rate Limit Test Controller");
        health.put("timestamp", System.currentTimeMillis());
        health.put("version", "1.0.0");
        
        return ResponseEntity.ok(health);
    }

    /**
     * 执行Sentinel限流测试
     * 发送消息到RocketMQ，观察Sentinel消费者的限流效果
     */
    private void performSentinelRateLimitTest(int messageCount) {
        log.info("开始执行Sentinel限流测试，发送消息数量: {}", messageCount);

        messageProducerService.sendBatchMessages(messageCount);
        log.info("Sentinel限流测试完成，已发送 {} 条消息到RocketMQ，等待消费者处理", messageCount);
        log.info("请观察Sentinel消费者的限流效果，当前消费者统计: {}", 
                sentinelConsumerService.getConsumptionStats());
    }

//    /**
//     * 执行Sentinel压力测试
//     * 持续发送消息到RocketMQ，测试Sentinel消费者的限流稳定性
//     */
//    private void performSentinelPressureTest(int duration, int messagesPerSecond) {
//        log.info("开始执行Sentinel压力测试，持续时间: {}秒, 每秒消息数: {}", duration, messagesPerSecond);
//
//        long startTime = System.currentTimeMillis();
//        long endTime = startTime + (duration * 1000L);
//
//        while (System.currentTimeMillis() < endTime) {
//            long batchStartTime = System.currentTimeMillis();
//
//            messageProducerService.sendBatchMessages();
//            long batchEndTime = System.currentTimeMillis();
//            long batchDuration = batchEndTime - batchStartTime;
//            long sleepTime = Math.max(0, 1000 - batchDuration);
//
//            if (sleepTime > 0) {
//                try {
//                    Thread.sleep(sleepTime);
//                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();
//                    break;
//                }
//            }
//        }
//
//        log.info("Sentinel压力测试完成，已发送 {} 条消息到RocketMQ", totalSent.get());
//        log.info("请观察Sentinel消费者的限流效果，当前消费者统计: {}",
//                sentinelConsumerService.getConsumptionStats());
//    }

//    /**
//     * 执行Sentinel突发流量测试
//     * 突发发送大量消息到RocketMQ，测试Sentinel消费者的限流响应
//     */
//    private void performSentinelBurstTest(int burstSize) {
//        log.info("开始执行Sentinel突发流量测试，突发消息数量: {}", burstSize);
//
//        for (int i = 0; i < burstSize; i++) {
//            final int messageId = i;
//            new Thread(() -> {
//                try {
//                    // 发送消息到RocketMQ
//                    String messageContent = "Sentinel突发测试消息-" + (messageId + 1);
//                    messageProducerService.sendMessage(messageContent);
//
//                    messagesSent.incrementAndGet();
//                    totalSent.incrementAndGet();
//
//                    log.info("✅ 突发测试消息 {} 已发送到RocketMQ: {}", messageId + 1, messageContent);
//
//                } catch (Exception e) {
//                    log.error("突发测试消息 {} 发送失败", messageId + 1, e);
//                }
//            }).start();
//        }
//
//        log.info("Sentinel突发流量测试启动完成，突发消息数量: {}", burstSize);
//        log.info("请观察Sentinel消费者的限流效果，当前消费者统计: {}",
//                sentinelConsumerService.getConsumptionStats());
//    }

//    /**
//     * 执行Sentinel配置测试
//     * 发送消息到RocketMQ，验证Sentinel消费者的限流规则配置
//     */
//    private void performConfigTest(int testCount) {
//        log.info("开始执行Sentinel配置测试，测试消息数量: {}", testCount);
//
//        for (int i = 0; i < testCount; i++) {
//            try {
//                // 发送消息到RocketMQ
//                String messageContent = "Sentinel配置测试消息-" + (i + 1);
//                messageProducerService.sendMessage(messageContent);
//
//                messagesSent.incrementAndGet();
//                totalSent.incrementAndGet();
//
//                log.info("✅ 配置测试消息 {} 已发送到RocketMQ: {}", i + 1, messageContent);
//
//                // 短暂延迟，便于观察限流效果
//                Thread.sleep(200);
//
//            } catch (Exception e) {
//                log.error("配置测试消息 {} 发送失败", i + 1, e);
//            }
//        }
//
//        log.info("Sentinel配置测试完成，已发送 {} 条消息到RocketMQ", testCount);
//        log.info("请观察Sentinel消费者的限流效果，当前消费者统计: {}",
//                sentinelConsumerService.getConsumptionStats());
//    }

}
